<template>
	<el-dialog :title="form.id ? '编辑安装点' : '绑定安装点'" v-model="visible" destroy-on-close :close-on-click-modal="false" draggable width="680px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="130px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="20" class="mb20" v-if="!!rowId || !!form.id">
					<el-form-item label="IMEI" prop="deviceId">
						<span>{{ form.imei }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20" v-else>
					<el-form-item label="IMEI" prop="deviceId">
						<el-select
							v-model="form.deviceId"
							filterable
							remote
							reserve-keyword
							placeholder="请输入"
							remote-show-suffix
							:remote-method="remoteMethod"
							:loading="imeiLoading"
							@change="handleImeiChange"
						>
							<el-option v-for="item in imeiOptions" :key="item.id" :label="item.imei" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20" v-if="form.deviceId">
					<el-form-item label="类型-型号">
						<div>{{ form.deviceType }}-{{ form.deviceModelName }}</div>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="单位" prop="deptId">
						<el-tree-select
							v-model="form.deptId"
							:data="parentData"
							:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
							clearable
							filterable
							check-strictly
							:disabled="!form.deviceId || !!form.id"
							default-expand-all
							:render-after-expand="false"
							placeholder="请选择授权单位"
							ref="treeRef"
							@change="handleDeptChange"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="建筑物" prop="buildingId">
						<el-select v-model="form.buildingId" filterable placeholder="请选择" :disabled="!form.deviceId" @change="handleBuildChange">
							<el-option v-for="item in buildingOptions" :key="item.id" :label="item.buildingName" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle :disabled="!form.deviceId" @click="BuildingDialogRef.openDialog()"></el-button>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="楼层" prop="floorId">
						<el-select v-model="form.floorId" filterable placeholder="请选择" :disabled="!form.buildingId">
							<el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle :disabled="!form.buildingId" @click="FloorDialogRef.openDialog()"></el-button>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="接警联系人" prop="alarmWorkerId">
						<el-select v-model="form.alarmWorkerId" filterable placeholder="请选择" :disabled="!form.deptId">
							<el-option v-for="item in contactOptions" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle :disabled="!form.deptId" @click="ContactDialogRef.openDialog()"></el-button>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="地图标记" prop="longitude">
						<el-button type="primary" icon="location" @click="AMapDialogRef.openDialog(form)">精确选择</el-button>
						<span class="ml-1">{{ form.longitude }}</span>
						<span class="ml-2">{{ form.latitude }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="详细地址" prop="detailAddress">
						<el-input v-model="form.detailAddress" placeholder="请输入详细地址" maxlength="250" />
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="安装点名称" prop="address">
						<el-input v-model="form.address" placeholder="请输入安装点名称" maxlength="200" />
					</el-form-item>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="安装点备注" prop="remarks">
						<el-input autosize type="textarea" v-model="form.remarks" placeholder="请输入内容" maxlength="500" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 地图精确选择 -->
	<AMapDialog ref="AMapDialogRef" @confirm="handleAMapConfirm" />
	<!-- 新增建筑物 -->
	<BuildingDialog ref="BuildingDialogRef" @refresh="getBuidingAndContactAll(form.deptId)" />
	<!-- 新增楼层 -->
	<FloorDialog ref="FloorDialogRef" @refresh="getFloorByBuilding(form.buildingId)" />
	<!-- 新增接警人 -->
	<ContactDialog ref="ContactDialogRef" @refresh="getBuidingAndContactAll(form.deptId)" />
</template>

<script setup lang="ts" name="BasicInstallLocationDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/installation/basicInstallLocation';
import { fetchListAll, getObj as getDeviceObj } from '/@/api/platform/basicDevice';
import { fetchListAll as fetchBuildingListAll, getObj as getBuidingObj } from '/@/api/installation/basicPlaceBuilding';
import { fetchListAll as fetchFloorListAll } from '/@/api/installation/basicPlaceFloor';
import { fetchListAll as fecthContactListAll } from '/@/api/installation/basicAlarmContacts';
import { deptTree } from '/@/api/admin/dept';
import { rule } from '/@/utils/validate';
const AMapDialog = defineAsyncComponent(() => import('../basicPlaceBuilding/components/AMap.vue'));
const BuildingDialog = defineAsyncComponent(() => import('../basicPlaceBuilding/form.vue'));
const FloorDialog = defineAsyncComponent(() => import('../basicPlaceFloor/form.vue'));
const ContactDialog = defineAsyncComponent(() => import('../basicAlarmContacts/form.vue'));
const emit = defineEmits(['refresh']);
const BuildingDialogRef = ref();
const FloorDialogRef = ref();
const ContactDialogRef = ref();
interface ListItem {
	id: string;
	imei: string;
	deviceTypeId: string;
	deviceModelId: string;
}
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const imeiLoading = ref(false);
const imeiOptions = ref<ListItem[]>([]);
const buildingOptions = ref<any[]>([]);
const floorOptions = ref<any[]>([]);
const contactOptions = ref<any[]>([]);
const parentData = ref([]);
const AMapDialogRef = ref();
const rowId = ref(null);
const oringinDeptId = ref();
// 定义字典

// 提交表单数据
const form = reactive({
	id: '',
	address: '',
	buildingId: '',
	buildingName: '',
	floorId: '',
	alarmWorkerId: '',
	longitude: '',
	latitude: '',
	detailAddress: '',
	remarks: '',
	deviceId: null,
	deptId: '',
	deviceType: '',
	deviceModelName: '',
	imei: '',
	ids: [],
});

// 定义校验规则
const dataRules = ref({
	deviceId: [{ required: true, message: '请选择设备ID', trigger: 'change' }],
	deptId: [{ required: true, message: '请选择单位', trigger: 'change' }],
	address: [{ required: true, message: '安装点名称不能为空', trigger: 'blur' }],
	alarmWorkerId: [{ required: true, message: '接警人员不能为空', trigger: 'change' }],
	longitude: [{ required: true, message: '请选择地图标记', trigger: 'blur' }],
	detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (row: any, isEdit = false) => {
	visible.value = true;
	form.id = '';
	form.deviceId = null;
	rowId.value = null;
	oringinDeptId.value = row?.deptId;
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	getDeptData();
	// 获取basicInstallLocation信息
	if (row.id && !isEdit) {
		rowId.value = row.id;
		form.deviceId = row.id;
		form.imei = row.imei;
		remoteMethod(row.imei);
		handleImeiChange(row.id);
	}
	if (row.id && isEdit) {
		getObj(row.id).then((res) => {
			Object.assign(form, res.data);
			remoteMethod(res.data.imei);
			getBuidingAndContactAll(res.data.deptId);
			getFloorByBuilding(res.data.buildingId);
		});
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	if (oringinDeptId.value !== form.deptId) {
		try {
			await useMessageBox().confirm('是否把该设备过户给这个单位？');
		} catch (e) {
			return;
		}
	}
	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const remoteMethod = (query: string) => {
	if (query) {
		imeiLoading.value = true;
		fetchListAll({ imeiLike: query })
			.then((res) => {
				imeiOptions.value = res.data;
			})
			.finally(() => {
				imeiLoading.value = false;
			});
	} else {
		imeiOptions.value = [];
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
const handleAMapConfirm = (data: any) => {
	const { lat, lng, address, building } = data;
	form.latitude = lat;
	form.longitude = lng;
	form.detailAddress = address;
	form.address = building;
};
const handleImeiChange = (id: string) => {
	getDeviceObj(id).then((res) => {
		form.deviceModelName = res.data.deviceModelName;
		form.deviceType = res.data.deviceType;
		form.deptId = res.data.deptId;
		oringinDeptId.value = res.data.deptId;
		handleDeptChange(res.data.deptId);
	});
};
// 选择单位-查询建筑物,接警人
const handleDeptChange = (id: string) => {
	form.buildingId = '';
	form.alarmWorkerId = '';
	form.floorId = '';
	getBuidingAndContactAll(id);
};
const getBuidingAndContactAll = (id: string) => {
	fetchBuildingListAll({ deptId: id }).then((res) => {
		buildingOptions.value = res.data;
	});
	fecthContactListAll({ deptId: id }).then((res) => {
		contactOptions.value = res.data;
	});
};
// 选择建筑物-查询楼层
const handleBuildChange = (id: string) => {
	form.floorId = '';
	getFloorByBuilding(id);
	getBuidingObj(id).then((res) => {
		form.latitude = res.data.latitude;
		form.longitude = res.data.longitude;
		form.detailAddress = res.data.detailAddress;
		form.address = res.data.buildingName;
	});
};
// 查询楼层
const getFloorByBuilding = (id: string) => {
	fetchFloorListAll({ buildingId: id }).then((res) => {
		floorOptions.value = res.data;
	});
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
